package com.aotuman.ktcoroutineandroid.chapter.javademo;

import kotlin.coroutines.Continuation;
import kotlin.coroutines.intrinsics.IntrinsicsKt;

public class SuspendLambda extends BaseContinuationImpl{
    private int label = 0;

    public static final Object COROUTINE_SUSPENDED = IntrinsicsKt.getCOROUTINE_SUSPENDED();

    public SuspendLambda(Continuation<Object> completion) {
        super(completion);
    }

    protected Object invokeSuspend(Object result){
        String resultStr;
        if (result == null) {
            resultStr = "";
        } else {
            resultStr = (String) result;
        }
        switch (label) {
            case 0: {
                System.out.println("现在label是:0, 将要执行returnSuspended");
                result = SuspendFunctions.returnSuspended(this);
                label++;
                System.out.println("将label设置为:"+label);
                System.out.println("returnSuspended result:"+result);
                if (isSuspended(result)) return COROUTINE_SUSPENDED;
                resultStr = (String) result;
                System.out.println("0 end---------------------------");
            }
            case 1: {
                System.out.println("现在label是:1, 将要执行returnImmediately1");
//                    result = DelayKt.delay(1000, this);
                result = SuspendFunctions.returnImmediately1(this);
                label++;
                System.out.println("将label设置为:"+label);
                System.out.println("returnImmediately1 result:"+result);
                if (isSuspended(result)) return COROUTINE_SUSPENDED;
                resultStr = resultStr + result;
                System.out.println("1 end---------------------------");
            }
            case 2: {
                System.out.println("现在label是:2, 将要执行returnImmediately2");
                result = SuspendFunctions.returnImmediately2(this);
                label++;
                System.out.println("将label设置为:"+label);
                System.out.println("returnImmediately2 result:"+result);
                if (isSuspended(result)) return COROUTINE_SUSPENDED;
                resultStr = resultStr + result;
                System.out.println("2 end---------------------------");
            }
            case 3:{
                System.out.println("现在label是:3");
                System.out.println("result:"+resultStr);
                return resultStr;
            }
            default:
                System.out.println("走到default");
                return resultStr;
        }
    }

    private boolean isSuspended(Object result) {
        return result == IntrinsicsKt.getCOROUTINE_SUSPENDED();
    }
}
